#pragma once

#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
#define MAX 1024

void handler(int sig)
{
    std::cout <<"调用了" << sig <<"信号" << std::endl;
}
class NameFifo
{
public:
    NameFifo(std::string path, std::string name)
        : _path(path), _name(name)
    {
        _pathname = _path + "/" + _name;

        umask(000);

        int ret = mkfifo(_pathname.c_str(), 0666);
        if (ret == 0)
        {

            std::cout << "创建命名管道成功" << std::endl;
        }
        else
        {
            ERR_EXIT("creat fifo :");
        }
    }

    ~NameFifo()
    {
        int ret = unlink(_pathname.c_str());
        if (ret == 0)
        {
            std::cout << " unlink " << _name << std::endl;
        }
        else
        {
            ERR_EXIT("unlink :");
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _pathname;
};

class OpFifo
{
public:
    OpFifo(std::string path, std::string name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open for read :");
        }
    }

    void OpenForWirte()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open for write :");
        }
    }

    void Write()
    {
        std::string massage;
        std::getline(std::cin , massage);
        massage = "Client say :" + massage;
        signal(13 , handler);
        int ret = write(_fd , massage.c_str() , massage.size());
        if(ret < 0)
        {
            ERR_EXIT("write :");
        }
    }

    void Read()
    {
        char massage [MAX];
        signal(13 , handler);

        int num = read(_fd , massage , sizeof(massage)-1);
        if(num < 0)
        {
            ERR_EXIT("read :");
        }
        else if(num == 0)
        {
            std::cout << "写端关闭，读端也关闭！" << std::endl; 
            close(_fd);
        }
        else
        {
            std::cout << "Server receive : " << massage << std::endl;
        }
    }

    ~OpFifo()
    {
        close(_fd);
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};